package leetcode.median;

/**
 * ClassName: $43_FindFirstAndLast
 * Description:
 * date: 2021-10-25 17:04
 *
 * @author liyifan
 */
public class $34_FindFirstAndLast {
    public int[] searchRange(int[] nums, int target) {
        if(nums.length == 0) {
            return new int[]{-1, -1};
        }
        return new int[]{leftBoundary(nums, target), rightBoundary(nums, target)};
    }
    int leftBoundary(int[] nums, int target) {
        int left = 0, right = nums.length - 1, mid = 0;
        while (left < right) {
            mid = (left + right) >> 1;
            if (nums[mid] == target) {
                right = mid;
            }
            else if (nums[mid] > target) {
                right = mid;
            }
            else if (nums[mid] < target) {
                left = mid + 1;
            }
        }
        return (nums[left] == target) ? left : -1;
    }

    int rightBoundary(int[] nums, int target) {
        int left = 0, right = nums.length - 1, mid = 0;
        while (left < right) {
            mid = (left + right + 1) >> 1;
            if (nums[mid] == target) {
                left = mid;
            } else if (nums[mid] > target) {
                right = mid - 1;
            } else if (nums[mid] < target) {
                left = mid;
            }
        }
        return (nums[left] == target) ? left : -1;
    }
}
